package per.dg.multiprocesskotlin.messenger

import android.app.ActivityManager
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import android.view.View
import per.dg.multiprocesskotlin.R

class MessengerClientActivity : AppCompatActivity() {

    private val TAG = "MessengerClientActivity"

    //    服务端 Messenger，通过 Messenger 发送消息，通过服务端的 handeler 接受
    lateinit var messenger : Messenger

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_messenger_client)
    }

    fun onClick(view: View) {
        startAndBindService()
    }

    fun startAndBindService(){
        //        启动服务
        startService(Intent(this, MessengerService::class.java))
        //        绑定服务
        bindService(Intent(this, MessengerService::class.java), serviceConnection, Service.BIND_AUTO_CREATE)
    }

    val serviceConnection : ServiceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {

        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            //通过服务端返回的Binder创建Messenger
            messenger = Messenger(service)

            sendDataToService(1)
        }
    }

    //    发送数据到服务断
    fun sendDataToService(i : Int){
        //创建消息，通过Bundle传递数据
        val message: Message = Message.obtain(null, MESSAGE_FROM_CLIENT)
        val bundle = Bundle()
        bundle.putString("msg", "hello service,this is client")
        message.setData(bundle)

        message.replyTo = mClientMessenger;

        try {
            //向服务端发送消息
            messenger.send(message)
        } catch (e: RemoteException) {
            e.printStackTrace()
        }
    }

    var mMessengerHandler : Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when(msg.what){
                MESSAGE_FROM_SERVICE -> {
                    Log.e(TAG, "receive message from service:" + msg.getData().getString("msg"));
                }
                else -> {
                    super.handleMessage(msg)
                }
            }
        }
    }

    val mClientMessenger : Messenger = Messenger(mMessengerHandler)

    override fun onDestroy() {
        super.onDestroy()
        unbindService(serviceConnection)
    }
}